<template>
  <div>
    <Form ref="formInline" :model="query" inline>
      <FormItem prop="username">
        <Input type="text" v-model="query.username" placeholder="用户名称">
          <Icon type="ios-person-outline" slot="prepend"></Icon>
        </Input>
      </FormItem>
      <FormItem>
        <Button type="primary" @click="search">查询</Button>
        <Button type="warning" @click="add">新增</Button>
      </FormItem>
    </Form>
    <Table border :columns="columns" :data="tableData">
      <template slot-scope="{ row }" slot="sex">
        {{ row.sex === 1 ? "男" : "女" }}
      </template>
      <template slot-scope="{ row }" slot="action">
        <Button
          type="primary"
          size="small"
          style="margin-right: 5px"
          @click="auth(row.id)"
          >授权</Button
        >
        <Button
          type="primary"
          size="small"
          style="margin-right: 5px"
          @click="edit(row)"
          >编辑</Button
        >
        <Button type="error" size="small" @click="remove(row.id)">删除</Button>
      </template>
    </Table>
    <Page
      :total="total"
      :current="query.extend.current"
      :page-size="query.extend.size"
      show-sizer
      @on-change="toPage"
      @on-page-size-change="changeSize"
    />

    <Modal v-model="modelShow" :title="modelType === 1 ? '新增' : '编辑'">
      <Form ref="formValidate" :model="formValidate" :label-width="80">
        <FormItem
          label="用户名"
          prop="username"
          :rules="{
            required: true,
            message: '用户名必填',
            trigger: 'blur',
          }"
        >
          <Input v-model="formValidate.username" maxlength="20" />
        </FormItem>
        <FormItem label="年龄" prop="title">
          <InputNumber
            :max="10000"
            :min="1"
            v-model="formValidate.age"
          ></InputNumber>
        </FormItem>
        <FormItem label="性别" prop="sex">
          <Select v-model="formValidate.sex" placeholder="性别">
            <Option v-for="t in sexType" :key="t.id" :value="t.id">{{
              t.type
            }}</Option>
          </Select>
        </FormItem>
        <FormItem
          label="手机号"
          prop="phone"
          :rules="{
            required: true,
            message: '手机号必填',
            trigger: 'blur',
          }"
        >
          <Input
            v-model="formValidate.phone"
            placeholder="手机号"
            maxlength="15"
          />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" size="large" @click="modelShow = false"
          >取消</Button
        >
        <Button type="primary" size="large" @click="submit">确定</Button>
      </div>
    </Modal>
    <Modal v-model="authModeShow" title="用户授权">
      <Row>
        <Form :label-width="80">
          <FormItem label="角色选择">
            <Select
              v-model="findName"
              filterable
              :remote-method="findRole"
              placeholder="模糊查询选择角色"
              :loading="loading"
              @on-select="selectRole"
            >
              <Option v-for="r in roleList" :value="r.id" :key="r.id">{{
                r.name
              }}</Option>
            </Select>
          </FormItem>
          <FormItem label=""></FormItem>
          <FormItem label=""></FormItem>
          <FormItem label="已选角色">
            <Tag
              type="border"
              v-for="r in usrRoleList"
              :key="r.id"
              :name="r.id"
              closable
              color="success"
              @on-close="closeChecked"
              >{{ r.name }}</Tag
            >
          </FormItem>
        </Form>
      </Row>
      <div slot="footer">
        <Button type="primary" size="large" @click="authRoleSubmit"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  findPage,
  updAdminUsr,
  addAdminUsr,
  delAdminUsr,
  authRole
} from './usr'
import { adminUsrFindRoleList, findUsrRoleList } from '../role/role'
export default {
  name: 'usr',
  data () {
    return {
      query: {
        username: '',
        extend: {
          current: 1,
          size: 10,
          like: 'username'
        }
      },
      total: 100,
      columns: [
        {
          title: '名称',
          key: 'username'
        },
        {
          title: '性别',
          slot: 'sex'
        },
        {
          title: '年龄',
          key: 'age'
        },
        {
          title: '手机号',
          key: 'phone'
        },
        {
          title: '操作',
          slot: 'action',
          width: 200,
          align: 'center'
        }
      ],
      tableData: [],
      sexType: [
        { id: 0, type: '女' },
        { id: 1, type: '男' }
      ],
      modelShow: false,
      modelType: 1,
      formValidate: {},
      authModeShow: false,
      loading: false,
      findName: '',
      usrRoleList: [],
      authUsrId: '',
      roleList: []
    }
  },
  created () {
    this.findPage()
  },
  methods: {
    edit (row) {
      this.$refs.formValidate.resetFields()
      this.formValidate = Object.assign({}, row)
      this.modelShow = true
      this.modelType = 2
    },
    remove (id) {
      delAdminUsr(id).then((res) => {
        if (res.code === 401) {
          this.$Message.error(res.msg)
        } else {
          this.$Message.success('删除成功')
          this.search()
        }
        this.modelShow = false
      })
    },
    add () {
      this.$refs.formValidate.resetFields()
      this.formValidate = { age: 20, sex: 1 }
      this.modelShow = true
      this.modelType = 1
    },
    submit () {
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          if (this.modelType === 1) {
            addAdminUsr(this.formValidate).then((res) => {
              this.modelShow = false
              this.search()
              this.$Message.success('操作成功')
            })
          } else {
            updAdminUsr(this.formValidate).then((res) => {
              this.modelShow = false
              this.search()
              this.$Message.success('操作成功')
            })
          }
        }
      })
    },
    search () {
      this.query.extend.current = 1
      this.findPage()
    },
    findPage () {
      findPage(this.query).then((res) => {
        if (res.code === 200) {
          this.total = res.data.total
          this.query.extend.current = res.data.current
          this.tableData = res.data.records
        } else { this.$Message.error(res.msg) }
      })
    },
    toPage (current) {
      this.query.extend.current = current
      this.findPage()
    },
    changeSize (size) {
      this.query.extend.current = 1
      this.query.extend.size = size
      this.findPage()
    },
    auth (id) {
      this.findName = ''
      this.authModeShow = true
      this.getUsrRoleList(id)
    },
    getUsrRoleList (id) {
      findUsrRoleList(id).then((res) => {
        this.authUsrId = id
        this.usrRoleList = res.data || []
      })
    },
    findRole (name) {
      if (name) {
        this.loading = true
        adminUsrFindRoleList(name).then((res) => {
          this.roleList = res.data
          this.loading = false
        })
      }
    },
    selectRole (v) {
      if (!this.usrRoleList.some((r) => r.id === v.value)) {
        this.usrRoleList.push({ id: v.value, name: v.label })
      }
    },
    closeChecked (e, v) {
      this.usrRoleList = this.usrRoleList.filter((f) => f.id !== v)
    },
    authRoleSubmit () {
      authRole({
        usrId: this.authUsrId,
        roleIds: this.usrRoleList.map((r) => r.id)
      }).then((res) => {
        if (res.code === 200) {
          this.authModeShow = false
        } else {
          this.$Message.error(res.msg)
        }
      })
    }
  }
}
</script>
